package com.weather.data.utils;

import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Component
public class VerificationCode {
 
    //设置验证码图片的宽、高
    private final int width = 100;
    private final int height = 30;
    private Image image;
    private String[] fontNames = new String[]{"微软雅黑","宋体","楷体","黑体"};
    //设置验证码的内容范围
    private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //验证码的内容
    private String text;
 
    /*
    * 设置随机code的颜色
    * */
    public Color getColor(){
        int Red = new Random().nextInt(150);
        int Blue = new Random().nextInt(150);
        int Green = new Random().nextInt(150);
        return new Color(Red,Green,Blue);
    }
 
    /*
    * 设置随机font的种类
    * */
    public Font getFont(){
        String name = fontNames[ new Random().nextInt(4) ];
        int style = new Random().nextInt(4);
        int size = new Random().nextInt(5)+24;
        return new Font(name,style,size);
    }
 
 
    /*
    * 创建一个验证码图片对象，
    * */
    public BufferedImage getImage(){
        //创建一个BufferImage，它可以在内存中操作
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics2D g2D = (Graphics2D) image.getGraphics();
        g2D.fillRect(0,0,width,height);
        //设置验证码的背景图案为白色
        g2D.setBackground(Color.white);
        StringBuilder text = new StringBuilder();
        //生成4个code形成验证码内容
        for(int i=0;i<4;i++){
            char r = codes.charAt( new Random().nextInt(62) );
            text.append(r);
            g2D.setColor( getColor() );
            g2D.setFont( getFont() );
            g2D.drawString(String.valueOf(r),i*25,height-8);
        }
        this.text = text.toString();
        return image;
    }
 
    /*
    *
    * */
    public String getText(){
        return this.text;
    }
 
}